package org.rcgwt.client.ui.validator.impl;

import java.util.Date;
import java.util.Map;

import org.rcgwt.client.ui.validator.IClientValidatorContext;
import org.rcgwt.client.ui.validator.IConverter;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Widget;

/**
 * A typed DateConverter. It can return a object representation of a string.
 * 
 * @author Elian ORIOU
 */

public class DateConverter implements IConverter<Date> {

	private static final String DATE_MONTH_YEAR_FORMAT = "dmy";

	private static final String MONTH_DATE_YEAR_FORMAT = "mdy";

	private static final String DEFAULT_FORMAT = DATE_MONTH_YEAR_FORMAT;

	private static final String DEFAULT_DATE_SEPARATOR = "/";

	private final DateTimeFormat dateTimeFormat;

	public DateConverter(Map<String, String> parameters) {
		dateTimeFormat = computeDateTimeFormat(parameters);
	}

	@Override
	public Date getAsObject(IClientValidatorContext context, Widget component,
			String value) {

		return dateTimeFormat.parse(value);
	}

	@Override
	public String getAsString(IClientValidatorContext context,
			Widget component, Date value) {
		return dateTimeFormat.format(value);
	}

	protected static DateTimeFormat computeDateTimeFormat(
			Map<String, String> parameters) {
		String format = DEFAULT_FORMAT;
		if (parameters.containsKey("date.format")) {
			format = parameters.get("date.format");
		}

		String sepSign = DEFAULT_DATE_SEPARATOR;
		if (parameters.containsKey("date.sepSign")) {
			String ds = parameters.get("date.sepSign");
			if (ds.length() > 0) {
				sepSign = ds.substring(0, 1);
			} else {
				sepSign = "";
			}
		}

		if (DATE_MONTH_YEAR_FORMAT.equals(format)) {
			return DateTimeFormat.getFormat("dd" + sepSign + "MM" + sepSign
					+ "yyyy");
		}

		if (MONTH_DATE_YEAR_FORMAT.equals(format)) {
			return DateTimeFormat.getFormat("MM" + sepSign + "dd" + sepSign
					+ "yyyy");
		}

		return DateTimeFormat.getShortDateFormat();
	}
}
